<?php
namespace serv\task\purchase;

use L;
use of;

class stock
{
    //计算采购在中途的库存数据
    public static function calcProduceStock()
    {
        //更新本地仓所有在产的数量为0
        $warehouseId = of::config('env.DEFAULT_LOCAL_WAREHOUSE');
        $warehouse_id = is_array($warehouseId) ? implode("','", $warehouseId) : $warehouseId;
        $sql = "UPDATE stock SET on_produce = 0 WHERE 1 AND warehouse_id IN ('{$warehouse_id}');";
        L::sql($sql, 'warehouse');

        //采购中及部分入库的库存更新到在产
        $sql = "SELECT purchase_data FROM purchase_order WHERE 1 AND status IN (20, 30)";
        $result = L::sql($sql, 'purchase');
        if (!empty($result)) {
            $purchaseData = [];
            foreach ($result as $v) {
                $orderData = json_decode($v['purchase_data'], true);
                foreach ($orderData as $pd) {
                    $purchaseData[] = $pd;
                }
            }

            //去重
            $purchaseData = array_unique($purchaseData);
            //统计汇总
            $sql = "SELECT a.sku, SUM(a.purchase_qty - a.arrive_qty) AS total, b.belong FROM purchase_sku AS a 
                    LEFT JOIN purchase AS b ON a.purchase_id = b.purchase_id
                    WHERE 1 AND b.purchase_no IN('".implode("','", $purchaseData)."')
                    GROUP BY a.sku, b.belong;";
            $rows = L::sql($sql, 'purchase');
            if (!empty($rows)) {
                foreach ($rows as $row) {
                    $sql = "UPDATE `stock` SET on_produce = '{$row['total']}' WHERE 1 
                            AND warehouse_id IN ('{$warehouse_id}') 
                            AND sku = '{$row['sku']}'
                            AND belong = '{$row['belong']}';";
                    L::sql($sql, 'warehouse');
                }
            }
        }
    }

}